﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Collections.ObjectModel;
using System.Web.UI.WebControls;

namespace ProtoTypeService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class ProtoTypeService : IProtoTypeService
    {
        string AppPath = AppDomain.CurrentDomain.BaseDirectory;
        string filepath = string.Empty;


        public string CreateForm(string formName, string description)
        {
            filepath = Path.Combine(AppPath, "App_Data\\forms.xml");


            if (!File.Exists(filepath))
            {
                //create a new file 
                XElement form = new XElement("forms",
                                       new XElement("form", new XElement("id", 1),
                                       new XElement("name", formName),
                                       new XElement("description", description)));
                form.Save(filepath);
            }
            else
            {
                int id = 0;
                XElement formdoc = XElement.Load(filepath);

                //obtain a Max formid from forms
                IEnumerable<XElement> singleform = (from f in formdoc.Elements("form")
                                                    orderby (int)f.Element("id") descending
                                                    select f);

                foreach (XElement xe in singleform)
                {
                    id = int.Parse(xe.Element("id").Value);
                    break;
                }
                id = id + 1;

                //Adding new Record to forms
                XElement newBook = new XElement("form", new XElement("id", id),
                                       new XElement("name", formName),
                                       new XElement("description", description));
                formdoc.Add(newBook);
                formdoc.Save(filepath);

            }
            return "success";
        }

        public List<XElement> LoadformList()
        {
            filepath = Path.Combine(AppPath, "App_Data\\forms.xml");

            List<XElement> formelements = new List<XElement>();
            if (File.Exists(filepath))
            {
                XElement formdoc = XElement.Load(filepath);
                var forms = (from f in formdoc.Elements("form") select f);
                formelements = forms.ToList();
            }
            return formelements;
        }

        public string CreateFormControl(string formid, string controName, string contolType, string controldataType)
        {
            filepath = Path.Combine(AppPath, "App_Data\\formcontrols.xml");

            if (!File.Exists(filepath))
            {

                int id = 1;
                //create new document 
                XElement formcontrol = new XElement("formcontrols",
                                 new XElement("form", new XAttribute("id", formid),
                                     new XElement("control",
                                      new XAttribute("id", id.ToString()),
                                        new XElement("cname", controName),
                                         new XElement("ctype", contolType),
                                         new XElement("cdataType", controldataType),
                                         new XElement("binding", id))));

                formcontrol.Save(filepath);
            }
            else
            {

                int id = 1;
                XElement formcontroldoc = XElement.Load(filepath);

                //obtain a Max formid from forms
                IEnumerable<XElement> formcontrols = (from fc in formcontroldoc.Descendants("form") where fc.Attribute("id").Value == formid select fc);

                if (formcontrols.ToList().Count != 0)
                {
                    XElement element = formcontrols.ElementAt(0);
                    id = element.Elements("control").Count();
                    id = id + 1;
                    element.Add(new XElement("control",
                                     new XAttribute("id", id),
                                     new XElement("cname", controName),
                                     new XElement("ctype", contolType),
                                     new XElement("cdataType", controldataType),
                                     new XElement("binding", id)));
                }
                else
                {
                    XElement formcontrol = new XElement("form", new XAttribute("id", formid),
                            new XElement("control",
                                    new XAttribute("id", id),
                                    new XElement("cname", controName),
                                    new XElement("ctype", contolType),
                                    new XElement("cdataType", controldataType),
                                     new XElement("binding", id)));
                    formcontroldoc.Add(formcontrol);

                }

                formcontroldoc.Save(filepath);
            }
            return "";
        }


        public List<XElement> LoadformControlList(string formid)
        {
            filepath = Path.Combine(AppPath, "App_Data\\formcontrols.xml");

            List<XElement> formcontrolelements = new List<XElement>();
            if (File.Exists(filepath))
            {
                XElement formdoc = XElement.Load(filepath);

                var formcontrols = from fc in formdoc.Descendants("form")
                                   where fc.Attribute("id").Value == formid
                                   select fc;
                formcontrolelements = formcontrols.ToList();
            }
            return formcontrolelements;
        }


        public string SetformLayout(string formid, string layouttype)
        {

            filepath = Path.Combine(AppPath, "App_Data\\forms.xml");

            if (File.Exists(filepath))
            {
                XElement formdoc = XElement.Load(filepath);

                var forms = from form in formdoc.Descendants("form")
                            where form.Element("id").Value == formid
                            select form;
                if (forms.Elements().Count() != 0)
                {
                    XElement element = forms.ElementAt(0);
                    if (element.Element("layout") != null)
                    {
                        element.Elements("layout").Remove();
                    }
                    element.Add(new XElement("layout", new XAttribute("type", layouttype)));
                }
                formdoc.Save(filepath);
            }
            return "";
        }

        public string SetformDetailLayout(string formid, string detaillayouttype)
        {

            filepath = Path.Combine(AppPath, "App_Data\\forms.xml");

            if (File.Exists(filepath))
            {
                XElement formdoc = XElement.Load(filepath);

                var forms = from form in formdoc.Descendants("form")
                            where form.Element("id").Value == formid
                            select form;
                if (forms.Elements().Count() != 0)
                {
                    XElement element = forms.ElementAt(0);
                    if (element.Element("detaillayout") != null)
                    {
                        element.Elements("detaillayout").Remove();
                    }
                    element.Add(new XElement("detaillayout", new XAttribute("type", detaillayouttype)));
                }
                formdoc.Save(filepath);
            }
            return "";
        }


        public void SetBindingelements(string formid, string tag, string Selecteditem, string cName)
        {
            filepath = Path.Combine(AppPath, "App_Data\\forms.xml");


            if (File.Exists(filepath))
            {
                XElement Xdoc = XElement.Load(filepath);

                var selectedform = from form in Xdoc.Descendants("form")
                                   where form.Element("id").Value == formid
                                   select form;
                if (selectedform.Elements().Count() != 0)
                {
                    XElement element = selectedform.ElementAt(0);
                    string layouttype = element.Element("layout").Attribute("type").Value;

                    if (element.Element("layout").Element(tag) != null)
                    {

                        element.Element("layout").Element(tag).Element("bid").Value = Selecteditem;
                        element.Element("layout").Element(tag).Element("name").Value = cName.ToString();
                    }
                    else
                    {
                        element.Element("layout").Add(new XElement(tag,
                           new XElement("bid", Selecteditem),
                           new XElement("name", cName)));
                    }


                    Xdoc.Save(filepath);

                }
            }
        }

        public void SetDetailBindingelements(string formid, string tag, string Selecteditem, string cName)
        {
            filepath = Path.Combine(AppPath, "App_Data\\forms.xml");


            if (File.Exists(filepath))
            {
                XElement Xdoc = XElement.Load(filepath);

                var selectedform = from form in Xdoc.Descendants("form")
                                   where form.Element("id").Value == formid
                                   select form;
                if (selectedform.Elements().Count() != 0)
                {
                    XElement element = selectedform.ElementAt(0);
                    string layouttype = element.Element("detaillayout").Attribute("type").Value;

                    if (element.Element("detaillayout").Element(tag) != null)
                    {

                        element.Element("detaillayout").Element(tag).Element("bid").Value = Selecteditem;
                        element.Element("detaillayout").Element(tag).Element("name").Value = cName.ToString();
                    }
                    else
                    {
                        element.Element("detaillayout").Add(new XElement(tag,
                           new XElement("bid", Selecteditem),
                           new XElement("name", cName)));
                    }


                    Xdoc.Save(filepath);

                }
            }
        }

        public string GetSelectedLayOutType(string formId)
        {

            filepath = Path.Combine(AppPath, "App_Data\\forms.xml");


            string selecedlayouttype = "Simple";
            if (File.Exists(filepath))
            {
                XElement formlayoutdoc = XElement.Load(filepath);

                var selectedformlayout = from formlayout in formlayoutdoc.Descendants("form") where formlayout.Element("id").Value == formId select formlayout;
                if (selectedformlayout.Elements("layout").Count() != 0)
                {
                    foreach (XElement formlayout in selectedformlayout)
                    {
                        selecedlayouttype = formlayout.Element("layout").Attribute("type").Value;
                    }
                }

            }
            return selecedlayouttype;
        }

        public string GetSelectedDetailLayOutType(string formId)
        {

            filepath = Path.Combine(AppPath, "App_Data\\forms.xml");


            string selecedlayouttype = "Simple";
            if (File.Exists(filepath))
            {
                XElement formlayoutdoc = XElement.Load(filepath);

                var selectedformlayout = from formlayout in formlayoutdoc.Descendants("form") where formlayout.Element("id").Value == formId select formlayout;
                if (selectedformlayout.Elements("detaillayout").Count() != 0)
                {
                    foreach (XElement formlayout in selectedformlayout)
                    {
                        selecedlayouttype = formlayout.Element("detaillayout").Attribute("type").Value;
                    }
                }

            }
            return selecedlayouttype;
        }

        public void SaveModifiedlayout(string formId, string xamltemplate)
        {
            filepath = Path.Combine(AppPath, "App_Data\\formcontrols.xml");

            if (File.Exists(filepath))
            {
                XElement formcontrolsdoc = XElement.Load(filepath);

                //read the current data and add a new record or modify the old one 
                var formtemplate = from c in formcontrolsdoc.Descendants("form") where c.Attribute("id").Value == formId select c;
                if (formtemplate.ToList().Count != 0)
                {
                    XElement element = formtemplate.ElementAt(0);
                    element.Elements("Template").Remove();
                    if (xamltemplate != string.Empty)
                        element.Add(new XElement("Template", xamltemplate));

                }
                formcontrolsdoc.Save(filepath);

            }
        }

        public string GetModufiedTemplate(string formId)
        {

            filepath = Path.Combine(AppPath, "App_Data\\formcontrols.xml");
            string xaml = string.Empty;

            if (File.Exists(filepath))
            {
                XElement formcontrolsdoc = XElement.Load(filepath);
                var template = from temp in formcontrolsdoc.Descendants("form") where temp.Attribute("id").Value == formId select temp;
                foreach (var t in template)
                {
                    if (t.Element("Template") != null)
                        xaml = t.Element("Template").Value.ToString();
                }

                xaml = xaml.Replace("<DataTemplate>", "<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>");
                xaml = xaml.Replace("<mymap />", "<mymap:Map />");
            }
            return xaml;

        }

        public Dictionary<string, string> AddFormItemDetails(Dictionary<string, string> items, string formid)
        {

            string formname = GetSelectedformName(formid);

            filepath = Path.Combine(AppPath, "App_Data\\" + formname + ".xml");

            if (!File.Exists(filepath))
            {
                //create a new file 
                XElement root = new XElement(formname);

                XElement childele = new XElement("item", new XAttribute("id", 1));

                foreach (var s in items)
                {

                    XElement element = new XElement(s.Key);
                    element.Value = s.Value;
                    childele.Add(element);
                }
                root.Add(childele);
                root.Save(filepath);

            }
            else
            {

                int id = 0;
                XElement formdoc = XElement.Load(filepath);

                //obtain a Max formid from forms
                IEnumerable<XElement> formdetails = (from fd in formdoc.Elements("item")
                                                     orderby (int)fd.Attribute("id") descending
                                                     select fd);

                foreach (XElement xe in formdetails)
                {
                    id = int.Parse(xe.Attribute("id").Value);
                    break;
                }
                id = id + 1;

                //Adding new Record to forms
                XElement newBook = new XElement("item", new XAttribute("id", id));
                formdoc.Add(newBook);

                foreach (var s in items)
                {
                    XElement element = new XElement(s.Key);
                    element.Value = s.Value;
                    newBook.Add(element);
                }

                formdoc.Save(filepath);

            }
            return items;


        }

        public ObservableCollection<XElement> GetSelectedFormItemDetails(string formid)
        {
            ObservableCollection<XElement> formelements = new ObservableCollection<XElement>();
            string formname = GetSelectedformName(formid);
            filepath = Path.Combine(AppPath, "App_Data\\" + formname + ".xml");
            if (File.Exists(filepath))
            {
                XElement formdetaildoc = XElement.Load(filepath);

                var formdetails = (from fd in formdetaildoc.Elements("item") select fd);
                formelements = formdetails.ToObservableCollection();

            }
            return formelements;
        }

        public string GetSelectedformName(string formid)
        {
            filepath = Path.Combine(AppPath, "App_Data\\forms.xml");
            string formname = string.Empty;
            if (File.Exists(filepath))
            {
                XElement formcontroldoc = XElement.Load(filepath);

                var forms = (from f in formcontroldoc.Descendants("form") where f.Element("id").Value == formid select f);

                foreach (var f in forms)
                {
                    formname = f.Element("name").Value;
                    break;
                }

            }
            return formname;
        }

        public string GetSelectedControlType(string formid, string controlname)
        {
            filepath = Path.Combine(AppPath, "App_Data\\formcontrols.xml");
            string controltype = string.Empty;
            if (File.Exists(filepath))
            {
                XElement formcontroldoc = XElement.Load(filepath);
                var fctrl = from fc in formcontroldoc.Descendants("control") where formcontroldoc.Element("form").Attribute("id").Value == formid select fc;
                foreach (var f in fctrl)
                {
                    if (f.Element("cname").Value.Replace(" ", "") == controlname)
                    {
                        controltype = f.Element("ctype").Value;
                    }

                }

            }
            return controltype;

        }

        public string GetSelectedControlTypeById(string formid, string controlname)
        {
            filepath = Path.Combine(AppPath, "App_Data\\formcontrols.xml");
            string controltype = string.Empty;
            if (File.Exists(filepath))
            {
                XElement formcontroldoc = XElement.Load(filepath);
                var fctrl = from fc in formcontroldoc.Descendants("control") where formcontroldoc.Element("form").Attribute("id").Value == formid select fc;
                foreach (var f in fctrl)
                {
                    if (f.Element("cname").Value.Replace(" ", "") == controlname)
                    {
                        controltype = f.Element("ctype").Value;
                    }

                }

            }
            return controltype;

        }

        public string UpdateFormField(string formid, string controlid, string fieldname, string fieldtype)
        {
            filepath = Path.Combine(AppPath, "App_Data\\formcontrols.xml");
            if (File.Exists(filepath))
            {
                XElement formcontroldoc = XElement.Load(filepath);

                IEnumerable<XElement> formcontrols = (from fc in formcontroldoc.Descendants("form") where fc.Attribute("id").Value == formid select fc);

                IEnumerable<XElement> eles = from fe in formcontrols.Descendants("control") where fe.Attribute("id").Value == controlid select fe;
                foreach (XElement f in eles)
                {
                    f.Element("cname").Value = fieldname;
                    f.Element("ctype").Value = fieldtype;
                }

                formcontroldoc.Save(filepath);
            }
            return null;
        }

        public ObservableCollection<XElement> LoadlayoutControls(string formid)
        {

            filepath = Path.Combine(AppPath, "App_Data\\forms.xml");
            ObservableCollection<XElement> formlayoutcontrols = new ObservableCollection<XElement>();

            if (File.Exists(filepath))
            {
                XElement formlayoutdoc = XElement.Load(filepath);
                var layoutcontrols = from formlayout in formlayoutdoc.Descendants("form") where formlayout.Element("id").Value == formid select formlayout;
                formlayoutcontrols = layoutcontrols.ToObservableCollection();
            }

            return formlayoutcontrols;
        }


        //get selected formname & Layouttype
        public void GetSelectedFormData(string formid, out string formname, out string selectedlayout)
        {
            filepath = Path.Combine(AppPath, "App_Data\\forms.xml");

            formname = "";
            selectedlayout = "";
            if (File.Exists(filepath))
            {
                XElement formdatadoc = XElement.Load(filepath);

                var Selformdata = from formdata in formdatadoc.Descendants("form")
                                  where formdata.Element("id").Value == formid
                                  select formdata;


                foreach (XElement fdata in Selformdata)
                {
                    if (fdata.Element("layout") != null)
                    {
                        selectedlayout = fdata.Element("layout").Attribute("type").Value;
                    }
                    formname = fdata.Element("name").Value;
                }
            }
        }

        public void Savedatainwebservice(Stream myStream)
        {
            int len = 32 * 1028;
            string saveTo = filepath = Path.Combine(AppPath, "App_Data\\forms11.xml");
            FileStream writeStream = new FileStream(saveTo, FileMode.Create, FileAccess.Write);
            byte[] buffer = new byte[len];
            int read;
            while ((read = myStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                writeStream.Write(buffer, 0, read);
            }
            writeStream.Close();
        }
        public void SavefilestoCloud(byte[] myStream, string filename)
        {
            string saveTo = filepath = Path.Combine(AppPath, "App_Data\\" + filename);
            FileStream writeStream = new FileStream(saveTo, FileMode.Create, FileAccess.Write);           
            int read = myStream.Length;            
            writeStream.Write(myStream, 0, read);
            writeStream.Close();
        }      
    }
}
